<?php

namespace app\admin\controller;


use app\admin\model\System;
use think\Config;

/**
 * 文件操作类
 * Class FileOperation
 * @package app\admin\controller
 */
class FileOperation extends Base
{
    protected $files;

    /**
     * Author:Jack Wang
     * Time:2018-10-19 15:15:40
     * Describe:下载文件到到服务器
     * @param $file
     * @param string $newFileName
     * @param string $newFileDir
     * @return mixed
     */
    public function downloadFile($file,$newFileName = '',$newFileDir = ''){
        $dirExt = date("Ymd")."/";//添加年月入后缀
        //没有指定目录放入File目录
        if(empty($newFileDir)){
            $newFileDir = config("FileDefaultDir"). $dirExt;//获取默认File目录
            if(!is_dir($newFileDir)){//目录不存在穿件目录
                mkdir ($newFileDir,0777,true);//循环创建目录
            }
        }else{
            $newFileDir = $newFileDir. $dirExt;
            if(!is_dir($newFileDir)){//指定目录是否存在不存在创建
                mkdir ($newFileDir,0777,true);//循环创建目录
            }
        }
        $this->files['newFileDir'] = $newFileDir ;//获取文件目录
        if(is_array($file)) {
            foreach ($file as $key=>$val) {
                $this->files[$key]['state'] = false;
                if ($this->checkFileExists($val)) {
                    $val = str_replace("\\", '/', $val);//替换所有的\
                    $this->files[$key]['fileName'] = substr($file,strripos($val,"/")+1);
                    $this->files[$key]['ext'] = $this->getFileExt($file);
                    //没有新文件名称随机命名（下载文件为多个时候命名无效）
                    if (is_array($file)) {
                        $newFileName = md5(RandomString());//随机数获取文加名MD5
                    }
                    $this->files[$key]['newFileName'] = $newFileName;//获取新文件名称
                    $this->files[$key]['SaveName'] = $this->files['newFileDir'] . $this->files[$key]['newFileName'] .'.'. $this->files[$key]['ext'];
                    $file_get_contents = file_get_contents($val);//获取远程文件内容
                    $files = fopen($this->files[$key]['SaveName'], "w");
                    $this->files[$key]['state'] = fwrite($files, $file_get_contents);
                    fclose($files);
                }
            }
        }else{
            if ($this->checkFileExists($file)) {
                $file = str_replace("\\", '/', $file);//替换所有的\
                $this->files['fileName'] = substr($file,strripos($file,"/")+1);
                $this->files['ext'] = $this->getFileExt($file);
                if (empty($newFileName)) {
                    $newFileName = md5(RandomString());//随机数获取文加名MD5
                }
                $this->files['newFileName'] = $newFileName;//获取新文件名称
                $this->files['SaveName'] = $this->files['newFileDir'] . $this->files['newFileName'] .'.'. $this->files['ext'];
                $file_get_contents = file_get_contents($file);//获取远程文件内容
                $files = fopen($this->files['SaveName'], "w");
                $this->files['state'] = fwrite($files, $file_get_contents);
                fclose($files);
            }else{
                $this->files['state'] = false;
            }
        }
        return $this->files;
    }

    /**
     * Author:Jack Wang
     * Time:2018-10-19 14:22:55
     * Describe:获取文件类型
     * @param $file
     * @return bool|string
     */
    public function getFileExt($file){
        return substr($file,strripos($file,".")+1);
    }

    /**
     * Author:Jack Wang
     * Time:2018-10-19 14:05:13
     * Describe:判断文件是否存在
     * @param $file
     * @return bool
     */
    public function checkFileExists($file){
        // 远程文件
        if(strtolower(substr($file, 0, 4))=='http'){
            $header = get_headers($file, true);
            return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
            // 本地文件
        }else{
            return file_exists($file);
        }
    }

    //图片上传
    public function uploadImg($type = "",$returnType = 'json',$config = [],$thumb = [],$water = false){
        Config::load(APP_PATH.'extra/upload.php');//加载上传配置文件
        $UploadFileConfig = Config::get("UploadFileConfig");//获取配置
        $configImg = [];
        $type = !empty($type) ? $type : input("type/s");//有直接传入参数优先使用
        if(!empty($type)){//没有设置上传类型时候
            //判断是否有该配置存在
            if(!empty($UploadFileConfig[$type])){
                $configImg = !empty($config) ? $config : $UploadFileConfig[$type];//设置上传类型,有传入以传入为准
            }else{
                $result['code'] = 2;
                $result['msg'] = '没有该上传类型！';
            }
        }else{
            $configImg = $UploadFileConfig["default"];//设置默认上传类型
        }
        if (!empty($configImg)) {//上传文件类型是否存在
            $validate = $configImg["validate"];
            $file = request()->file('file');
            $info = $file->validate($validate)->move($configImg["path"]);
            if ($info) {
                $getSaveName = $info->getSaveName();//获取图片路径
                $getSaveName = str_replace("\\", '/', $getSaveName);//替换所有的\
                $result['code'] = 0;
                $result['msg'] = '上传成功！';
                $result['url'] = "/".$configImg["path"] . $getSaveName;
                $result['name'] = $info->getFilename();
                $result['ext'] = $info->getExtension();
                $this->handleImg(".".$result['url'],$thumb,$water);//处理图片
            } else {
                $result['code'] = 1;
                $result['msg'] = $file->getError();
            }
        } else {
            $result['code'] = 2;
            $result['msg'] = '设置上传类型出错！';
        }
        return $returnType == "json" ? json($result) : $result;
    }

    //处理图片
    public function handleImg($img_url,$thumb = [],$water = false){
            if(!empty($thumb)){//是否裁剪图片
                if(!empty($thumb[2]) && $thumb[2] !== false) {//生成透明缩略图
                    $image = \think\Image::pngthumb($img_url, $img_url, $thumb[0], $thumb[1]);
                }else {
                    $image = \think\Image::open($img_url);
                    $image->thumb($thumb[0], $thumb[1], \think\Image::THUMB_SCALING)->save($img_url);
                }
            }
            if($water){//是否打水印
                $System = new System();
                $dataInfo = $System->drawingUploadSystemInfo();
                if((int)$dataInfo["switch"] > 0) {
                    $image = \think\Image::open($img_url);
                    $image->water('.'.$dataInfo["right"], \think\Image::WATER_SOUTHEAST, 100)->water('.'.$dataInfo["center"], \think\Image::WATER_CENTER, 100)->save($img_url);
                }
            }

    }

    //移动文件
    public function movementFile($url,$newUrl){
        $urlDir = substr($newUrl,0,strrpos($newUrl,"/"));//获取目录
        //指定目录不存在创建
        if(!is_dir($urlDir)){//指定目录是否存在不存在创建
            mkdir ($urlDir,0777,true);//循环创建目录
        }
        return rename($url,$newUrl);
    }
}
